//import CostItem from "../controller/ui/cost_items"

import { Skill } from "../class/skill"
import JsonManager from "../manager/json_manager"
import MainManager from "../manager/main_manager"
import PoolManager from "../manager/pool_manager"
import StorageManager from "../manager/storage_manager"
import { Emitter } from "../utils/emmiter"
import { MessageType } from "../utils/message"
import { Utils } from "../utils/utils"

// import UIAnimaManager from "../manager/action_manager"

const { ccclass, property } = cc._decorator

interface OkCalBack {
    (isOK: boolean, param?: {}): void
}

@ccclass
export default class ExtraStatUIManager extends cc.Component {
    static instance: ExtraStatUIManager = null

    @property(cc.Node)
    uiNode: cc.Node = null

    @property(cc.Node)
    maskNode: cc.Node = null

    @property(cc.Label)
    labelTitle: cc.Label = null

    @property(cc.Label)
    labelDesc: cc.Label = null

    @property(cc.Button)
    nextBtn: cc.Button = null


    @property(cc.Button)
    prevBtn: cc.Button = null

    @property(cc.Button)
    openSkillBtn: cc.Button = null

    @property(cc.Button)
    buttonConfirm: cc.Button = null

    @property(cc.Button)
    drawButton: cc.Button = null

    @property(cc.Label)
    curLevelLable: cc.Label = null

    @property(cc.Prefab)
    itemPrefab: cc.Prefab = null

    @property(cc.ScrollView)
    scrollView: cc.ScrollView = null

    @property(cc.Node)
    content1: cc.Node = null; // ScrollView 的 Content 节点

    curCallBack: OkCalBack = null
    curParam: any = null

    unlockedItems = [0]; // 已解锁的项目索引
    totalItems = 25; // 总项目数量
    isDrawing = false; // 是否正在抽奖
    listIndex:number=0


    _isClick: boolean = false

    onLoad() {
        // console.log("PoolManager Onload");
        ExtraStatUIManager.instance = this

        this.maskNode.on('click', this.hideUI, this);
        this.drawButton.node.on('click', this.startLottery, this);
        // this.nextBtn.node.on("click", this.selectNextLeve, this)
       
        // this.openSkillBtn.node.on("click", this.openSkill, this)
    

        if (this.uiNode.active) {
            this.uiNode.active = false
        }

    }





    async startLottery() {
        if (this.isDrawing) return;

        this.isDrawing = true;
        this.drawButton.getComponent(cc.Button).interactable = false; // 禁用按钮

        // 获取未解锁的项目索引
        const lockedItems = Array.from({ length: this.totalItems }, (_, i) => i).filter(
            (i) => !this.unlockedItems.includes(i)
        );
        cc.log('xxxxxxxxx')
        if (lockedItems.length === 0) {
            console.log("所有项目已解锁！");
            this.isDrawing = false;
            this.drawButton.getComponent(cc.Button).interactable = true;
            return;
        }
        const selectedIndex = await this.runRandomLotteryEffect(lockedItems);
        cc.log("选中", selectedIndex)
        // 更新解锁状态
        // this.unlockedItems.push(selectedIndex);
        StorageManager.instance.levelInfo.statIds.push(selectedIndex)
        this.unlockedItems  =StorageManager.instance.levelInfo.statIds;
        StorageManager.instance.savePlayerData()
        // 刷新界面
        this.populateScrollView();

        // 恢复按钮交互
        this.isDrawing = false;
        this.drawButton.getComponent(cc.Button).interactable = true;
    }

    // 模拟随机走马灯效果
    runRandomLotteryEffect(lockedItems) {
        let preIndex = -1
        return new Promise((resolve) => {
            const highlightDuration = 200; // 每次高亮持续时间（毫秒）
            const totalHighlights = 20; // 总共高亮次数
            let currentHighlightCount = 0;

            const highlightItem = (index, highlight) => {
                const itemNode = this.content1.getChildByName(`Item-${lockedItems[index]}`);
                if (itemNode) {
                    itemNode.scale = highlight ? 1.1 : 1;
                    itemNode.getComponent(cc.Button).interactable = highlight ? true : false
                    // 示例用法：
                    // highlightItem 是需要高亮的目标节点
                    // scrollView 是你的 ScrollView 节点
                    this.scrollView.scrollTo(cc.v2(itemNode.x, itemNode.y), 0.1)
                }
            };

            const randomHighlightStep = () => {
                // 随机选择一个未解锁的索引
                const randomIndex = Math.floor(Math.random() * lockedItems.length);

                // 重置上一个高亮的项目
                if (currentHighlightCount > 0) {
                    // const previousIndex = Math.floor(Math.random() * lockedItems.length);
                    highlightItem(preIndex, false);
                }
                preIndex = randomIndex
                // 高亮当前随机选择的项目
                highlightItem(randomIndex, true);

                currentHighlightCount++;

                if (currentHighlightCount >= totalHighlights) {
                    setTimeout(() => {
                        highlightItem(randomIndex, false);
                        resolve(lockedItems[randomIndex]);
                    }, highlightDuration);
                } else {
                    setTimeout(randomHighlightStep, highlightDuration);
                }
            };

            randomHighlightStep();
        });
    }



    // 填充 ScrollView
    populateScrollView() {
        this.content1.removeAllChildren(); // 清空之前的内容
        let bonusData = Object.values(JsonManager.instance.getDataByName('stat_extra'))
        bonusData.forEach((data, index) => {
           let item = PoolManager.instance.createObjectByName('list_btn', this.content1)
            // 创建每一项

            const label = item.getComponentInChildren(cc.Label);
            if (label) {
                label.string = `${data.desc}`;
            }
            // 设置节点名称，便于定位
            item.name = `Item-${index}`;
            if(this.unlockedItems.includes(index)){
                item.getComponent(cc.Button).interactable = true
            }else{
                item.getComponent(cc.Button).interactable = false
            }
          
            // this.content1.addChild(item); // 添加到 Content
        });
        this.content1.getComponent(cc.Layout).updateLayout()
    }

    openSkill() {
        Emitter.fire(MessageType.openSkillList)
    }


    showUI(title: string, desc: string, callback: OkCalBack = null, param: {} = null, isNormal: boolean = true, labels: string[] = null) {
        if (!this.uiNode.active) {
            this.uiNode.active = true
            //  UIAnimaManager.instance.showDialog(this.uiNode, this.maskNode)
        }
        this.unlockedItems= StorageManager.instance.levelInfo.statIds
        this.populateScrollView()
       
        // this.refreshUI()
        this.curParam = param
    }

    refreshUI() {
        this.curLevelLable.string = '第' + StorageManager.instance.levelInfo.curLevel + '关';
    }

    selectNextLeve() {
        StorageManager.instance.levelInfo.curLevel++;
        if (StorageManager.instance.levelInfo.curLevel >= StorageManager.instance.levelInfo.maxLevel) {
            StorageManager.instance.levelInfo.curLevel = StorageManager.instance.levelInfo.maxLevel
        }
        this.refreshUI()
    }

    selectPreLeve() {
        StorageManager.instance.levelInfo.curLevel--;
        if (StorageManager.instance.levelInfo.curLevel < 1) {
            StorageManager.instance.levelInfo.curLevel = 1;
        }
        this.refreshUI()
    }

    enterGame() {
        cc.log('1')
        // StorageManager.instance.skills.push(this.ids[0])
        // this.notifyAdd()
        Emitter.fire(MessageType.gameStart)
        this.hideUI()
    }


    confirm() {

        this.hideUI()
    }
    hideUI() {
        this.uiNode.active = false
        cc.director.resume();
        //  AudioManager.instance.playAudio('ui_close')

    }
}
